﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using static System.Net.Mime.MediaTypeNames;

namespace LPBToolsLib
{
    /// <summary>
    /// JSON配置工具基础类
    /// 注意：目标文件必须已经创建，而且所有节点都已经创建，必须使用2级节点方式；
    /// appsettings.json文件为初始配置参考；
    /// </summary>
    public class JSONINISettings
    {
        private static string MutexKey = "JSONINISettings" + Guid.NewGuid().ToString();
        private Mutex tMutx = new Mutex(false, MutexKey);
        protected string FileName { get; private set; } = "";
        protected Dictionary<string, Dictionary<string, object>> AppSetting { get; private set; } = null;
        public JSONINISettings(FileInfo SetFile)
        {
            if (SetFile != null)
            {
                if (!File.Exists(SetFile.FullName))
                    File.WriteAllText(SetFile.FullName, "{}");
                if (File.Exists(SetFile.FullName))
                {
                    string sJSON = File.ReadAllText(SetFile.FullName);
                    if (!string.IsNullOrEmpty(sJSON))
                    {
                        AppSetting = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(sJSON);
                    }
                    FileName = SetFile.FullName;
                }
            }
        }

        public JSONINISettings(string SetFile):this(new FileInfo(SetFile))
        {            
        }

        public  T getCFGValue<T>(string Segment, string Name,T DefaultValue)
        {
            if ((AppSetting != null) && AppSetting.ContainsKey(Segment)
                && AppSetting[Segment].ContainsKey(Name))
            {
                return (T)AppSetting[Segment][Name];
            }
            return DefaultValue;
        }

        public void setCFGValue(string Segment, string Name, object value)
        {
            if (AppSetting != null)
            {
                tMutx.WaitOne();
                try
                {
                    if (AppSetting.ContainsKey(Segment))
                    {
                        if (AppSetting[Segment].ContainsKey(Name))
                            AppSetting[Segment][Name] = value;
                        else
                            AppSetting[Segment].Add(Name, value);
                    }
                    else
                    {
                        Dictionary<string, object> tSegment = new Dictionary<string, object>();
                        tSegment.Add(Name, value);
                        AppSetting.Add(Segment, tSegment);
                    }
                    File.WriteAllText(FileName, JsonConvert.SerializeObject(AppSetting));
                }
                finally
                {
                    tMutx.ReleaseMutex();
                }
            }
        }
    }
}
